package cn.openread.demo.netty.ws;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;


public final class WebSocketClient {

    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "18888"));

    public static void main(String[] args) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();

                            p.addLast("http-decode-encode", new HttpServerCodec());
                            p.addLast("http-aggregator", new HttpObjectAggregator(65535));
                            p.addLast("http-chunked", new ChunkedWriteHandler());

                            p.addLast("WebSocket-protocol", new WebSocketServerProtocolHandler("/ws", true));
                            p.addLast("ws-compress", new WebSocketServerCompressionHandler());
                            p.addLast("WebSocket-request", new ObjectWebSocketFrameHandler());
                            p.addLast(new EchoClientHandler());
                        }
                    });

            // 启动客户端
            ChannelFuture f = b.connect(HOST, PORT).sync();
            // 等待客户端链路关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出，释放线程池资源
            group.shutdownGracefully();
        }
    }
}
